import { fetchMaterialList, MaterialApi } from '@/api/premium/content/material'
import { QueryMaterialRequest } from '@/api/premium/content/model/materialModel'
import { MaterialItem } from '@/components/ItemList/MaterialList/types'
import { formatPagination } from '@/utils/antdOpFormatHelper'
import { computed, ref } from 'vue'
import { SMatDiaForm } from '../types'
import { Pagination } from '#/antd'
import { useStore } from '@/store'

const useSelectMatDialog = () => {
  const store = useStore()
  const SMatDiavisiable = ref<boolean>(false)
  const matList = ref<MaterialItem[]>([])
  const currentTemp = ref()
  const SMatDiaPageInfo = ref<Pagination>({
    current: 1,
    pageSize: 12,
    total: 0,
  })

  const searchMatData = async (
    queryData: SMatDiaForm,
    pageInfo: Pagination
  ) => {
    SMatDiaPageInfo.value.current = pageInfo.current
    SMatDiaPageInfo.value.pageSize = pageInfo.pageSize
    const reqData: QueryMaterialRequest = {
      ...queryData,
      current: SMatDiaPageInfo.value.current,
      size: SMatDiaPageInfo.value.pageSize,
    }
    const { data } = await fetchMaterialList({
      ...reqData,
    })
    const { records, ...pageInfoData } = data
    matList.value = records
    SMatDiaPageInfo.value = formatPagination(pageInfoData)
  }

  const initMatData = async () => {
    const reqData: QueryMaterialRequest = {
      current: SMatDiaPageInfo.value.current,
      size: SMatDiaPageInfo.value.pageSize,
    }
    const { data } = await fetchMaterialList({
      ...reqData,
    })
    const { records, ...pageInfoData } = data
    matList.value = records
    SMatDiaPageInfo.value = formatPagination(pageInfoData)
  }
  const queryMatLoading = computed(() =>
    store.getters['global/isOpLoading'](MaterialApi.GET_MATERIAL_LIST)
  )

  const openSMatDia = async (tempItem: unknown) => {
    currentTemp.value = tempItem
    await initMatData()
    SMatDiavisiable.value = true
  }

  return {
    SMatDiavisiable,
    openSMatDia,
    searchMatData,
    queryMatLoading,
    matList,
    SMatDiaPageInfo,
    currentTemp,
  }
}
export default useSelectMatDialog
